<template>
  <div class="page">
    <r-header />
    <main class="main">
      <div class="mycard">
        <img class="myimg" src="/assets/千寻.png">
        <div class="mail">{{ formatPhoneNumber($store.state.user.profile.phone_number) }}</div>
        
        <!-- 用户权益信息 -->
        <div class="benefit-info">
          <div class="benefit-item">
            <span class="benefit-label">剩余Token:</span>
            <span class="benefit-value">
              <span v-if="$store.state.user.profile.totalTokens === -1" class="unlimited">无限制</span>
              <span v-else>{{ $store.state.user.profile.totalTokens || 0 }}</span>
            </span>
          </div>

        </div>
      </div>
      <div class="cards">
        
        <div class="card" @click="goToTestHistory">
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
               class="cardimg">
            <path stroke-linecap="round" stroke-linejoin="round"
                  d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25zM6.75 12h.008v.008H6.75V12zm0 3h.008v.008H6.75V15zm0 3h.008v.008H6.75V18z" />
          </svg>
          <div class="txt">考试记录</div>
          <p class="">这里可以查询您的所有做题记录</p>
        </div>
        <div class="card" @click="goToPurchaseHistory">
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
               class="cardimg">
            <path stroke-linecap="round" stroke-linejoin="round"
                  d="M21 11.25v8.25a1.5 1.5 0 01-1.5 1.5H5.25a1.5 1.5 0 01-1.5-1.5v-8.25M12 4.875A2.625 2.625 0 109.375 7.5H12m0-2.625V7.5m0-2.625A2.625 2.625 0 1114.625 7.5H12m0 0V21m-8.625-9.75h18c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125h-18c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" />
          </svg>
          <div class="txt">购买记录</div>
          <p class="">查询所有套餐购买记录</p>
        </div>
        <div class="card">
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
               class="cardimg">
            <path stroke-linecap="round" stroke-linejoin="round"
                  d="M4.5 12a7.5 7.5 0 0015 0m-15 0a7.5 7.5 0 1115 0m-15 0H3m16.5 0H21m-1.5 0H12m-8.457 3.077l1.41-.513m14.095-5.13l1.41-.513M5.106 17.785l1.15-.964m11.49-9.642l1.149-.964M7.501 19.795l.75-1.3m7.5-12.99l.75-1.3m-6.063 16.658l.26-1.477m2.605-14.772l.26-1.477m0 17.726l-.26-1.477M10.698 4.614l-.26-1.477M16.5 19.794l-.75-1.299M7.5 4.205L12 12m6.894 5.785l-1.149-.964M6.256 7.178l-1.15-.964m15.352 8.864l-1.41-.513M4.954 9.435l-1.41-.514M12.002 12l-3.75 6.495" />
          </svg>
          <div class="txt">资料编辑</div>
          <p class="">在这里可以修改登录密码</p>
        </div>
        <div class="card" @click="goToShop">
          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
               class="cardimg">
            <path stroke-linecap="round" stroke-linejoin="round"
                  d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 00-16.536-1.84M7.5 14.25L5.106 5.272M6 20.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm12.75 0a.75.75 0 11-1.5 0 .75.75 0 011.5 0z" />
          </svg>
          <div class="txt">套餐购买</div>
          <p class="">无限制的对话</p>
        </div>
      </div>
    </main>
  </div>
</template>

<script type="text/javascript">
import { useStore } from 'vuex';
import { orderApi } from '@/api/product';
export default {
  name: "my",
  data() {
    return {
      paymentSuccess: false,
      orderId: '',
      amount: 0,
      totalTokens: 0
    }
  },

  props: {
  },
  computed: {
  },
  methods: {
    // 检查支付成功状态
    checkPaymentSuccess() {
      const query = this.$route.query;
      if (query.paymentSuccess === 'true') {
        this.paymentSuccess = true;
        this.orderId = query.orderId || '';
        this.amount = parseFloat(query.amount) || 0;
        
        // 显示支付成功提示
        setTimeout(() => {
          alert(`支付成功！\n订单号：${this.orderId}\n支付金额：¥${this.amount.toFixed(2)}`);
        }, 500);
        
        // 清除URL参数
        this.$router.replace('/my');
      }
    },
    
    // 跳转到购买记录页面
    goToPurchaseHistory() {
      this.$router.push('/purchase-history');
    },
    
    // 加载用户权益信息
    async loadUserBenefits() {
      try {
        // 优先使用数据库中的用户ID，如果没有则使用手机号
        const userId = this.$store.state.user.profile.id || this.$store.state.user.profile.phone_number;
        
        console.log('使用用户ID:', userId, '类型:', typeof userId);
        
        // 调用用户权益API
        const response = await this.getUserBenefits(userId);
        
        if (response.success) {
          console.log('用户权益数据:', response.data);
          this.totalTokens = response.data.totalTokens || 0;
        } else {
          console.error('获取用户权益失败:', response.message);
          // 使用默认值
          this.totalTokens = 0;
        }
      } catch (error) {
        console.error('加载用户权益失败:', error);
        // 使用默认值
        this.totalTokens = 0;
      }
    },
    
    // 获取用户权益信息
    async getUserBenefits(userId) {
      try {
        const response = await fetch(`http://localhost:8088/api/user/${userId}/benefits`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.$store.state.user.profile.token}`
          }
        });
        
        return await response.json();
      } catch (error) {
        console.error('获取用户权益失败:', error);
        return { success: false, message: '网络错误' };
      }
    }
  },
  methods: {
    // 检查支付成功
    checkPaymentSuccess() {
      const urlParams = new URLSearchParams(window.location.search);
      const paymentSuccess = urlParams.get('paymentSuccess');
      const orderId = urlParams.get('orderId');
      const amount = urlParams.get('amount');
      
      if (paymentSuccess === 'true' && orderId && amount) {
        this.paymentSuccess = true;
        this.orderId = orderId;
        this.amount = amount;
        
        // 显示支付成功提示
        alert(`支付成功！\n订单号：${orderId}\n支付金额：${amount}元\n权益已更新到您的账户！`);
        
        // 清除URL参数
        window.history.replaceState({}, document.title, window.location.pathname);
      }
    },
    
    // 加载用户权益信息
    loadUserBenefits() {
      // 优先使用数据库中的用户ID，如果没有则使用手机号
      const userId = this.$store.state.user.profile.id || this.$store.state.user.profile.phone_number;
      if (userId) {
        this.getUserBenefits(userId);
      }
    },
    
    // 获取用户权益信息（从后端数据库获取）
    async getUserBenefits(userId) {
      try {
        console.log('从后端获取用户权益，用户ID:', userId);
        
        const response = await fetch(`http://localhost:8088/api/user/${userId}/benefits`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.$store.state.user.profile.token}`
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          if (data.success) {
            console.log('从后端获用户权益数据:', data,data);
            
            // 如果返回数据中包含用户ID，更新Vuex中的用户ID
            if (data.data.id) {
              this.$store.commit('user/updateUserId', data.data.id);
            }
            
            // 更新Vuex中的用户权益信息
            this.$store.commit('user/updateBenefit', data.data);
            
            // 更新本地数据
            this.totalTokens = data.data.totalTokens || 0;
            
            return data;
          } else {
            console.error('获取用户权益失败:', data.message);
            return { success: false, message: data.message };
          }
        } else {
          console.error('HTTP请求失败:', response.status);
          return { success: false, message: 'HTTP请求失败' };
        }
      } catch (error) {
        console.error('获取用户权益失败:', error);
        return { success: false, message: error.message };
      }
    },
    
    // 跳转到购买记录页面
    goToPurchaseHistory() {
      this.$router.push('/purchase-history');
    },
    
    // 跳转到商品页面
    goToShop() {
      this.$router.push('/shop');
    },
    
    // 跳转到考试记录页面
    goToTestHistory() {
      this.$router.push('/test-history');
    },
    
    // 格式化手机号显示
    formatPhoneNumber(phoneNumber) {
      if (!phoneNumber) {
        return '未设置手机号';
      }
      
      // 确保是字符串类型
      const phoneStr = String(phoneNumber);
      
      if (phoneStr.length >= 11) {
        return phoneStr.substring(0, 3) + '****' + phoneStr.substring(7);
      } else {
        return phoneStr; // 如果长度不够，直接显示
      }
    }
  },
  mounted() {
    this.checkPaymentSuccess();
    this.loadUserBenefits();
    
    // 如果是从支付成功页面跳转过来，刷新权益信息
    if (this.$route.query.paymentSuccess === 'true') {
      setTimeout(() => {
        this.loadUserBenefits();
      }, 2000); // 等待2秒让后端处理权益更新
    }
  },
}
</script>

<style lang="scss" scoped>
.page {
  background-color: #0f172a;
  max-width: 1280px;
  padding-top: 80px; // 为固定导航栏留出空间
}

.main {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

}

.mycard {
  display: flex;
  flex-direction: column;
  margin: 0rem 0 2rem;
  align-items: center;
  justify-content: center;
  color: #6986a0;
  cursor: pointer;

  .mail {
    font-size: large;
    font-size: 18px;
    margin: 5px 0;
    color: #ffffff;
  }
}

.myimg {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
}

/* 权益信息样式 */
.benefit-info {
  margin-top: 1rem;
  padding: 1rem;
  background: rgba(51, 65, 85, 0.3);
  border-radius: 8px;
  border: 1px solid rgba(179, 198, 217, 0.2);
  width: 100%;
  max-width: 300px;
}

.benefit-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
  font-size: 14px;
}

.benefit-item:last-child {
  margin-bottom: 0;
}

.benefit-label {
  color: #b3c6d9d6;
  font-weight: 500;
}

.benefit-value {
  color: #ffffff;
  font-weight: 600;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
  font-size: 13px;
}

.unlimited {
  background: linear-gradient(135deg, #10B981, #059669);
  color: #ffffff;
  font-weight: 700;
}

.cards {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.card {
  display: flex;
  flex-direction: column;
  // flex-wrap: wrap-reverse;
  padding: 1.5rem;
  border-radius: 10px;
  background: radial-gradient(164.75% 100% at 50% 0%, #334155 0%, #0F172A 48.73%);
  color: #b3c6d9d6;
  font-size: 13px;
  margin: 1rem 3rem;

  svg {

    color: #cbc9c9;
    width: 10%;
    height: 10%;
  }

  .txt {
    color: #cbc8c8;
    margin: 1rem 0 0.5rem 0;
    font-size: 18px;
  }
}

.card:hover {
  box-shadow: 0 0 5px #03e9f4, 0 0 10px #03e9f4, 0 0 15px #03e9f4,
}
</style>